﻿using B.S.BasicData.Api.Write.Applications.Commands.Accounts;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastcuture.Commons;
using B.S.BasicData.Infrastcuture.Interfaces;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Applications.CommandHandlers.Accounts
{
    public class DeleteQueryCommandHandler : IRequestHandler<DeleteQueryCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<UserInfo> baseRepository;
        private readonly IBaseRepository<NlogInfo> baseRepository1;


        public DeleteQueryCommandHandler(IBaseRepository<UserInfo> baseRepository, IBaseRepository<NlogInfo> baseRepository1)
        {
            this.baseRepository = baseRepository;
            this.baseRepository1 = baseRepository1;
        }

        public async Task<ApiResult<object>> Handle(DeleteQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result =new ApiResult<object>();
            result.Code=ResultCode.DeleteSuccess;
            result.Message = ResultCode.DeleteSuccess.Description();
            var list=baseRepository.GetAll().FirstOrDefault(x=>x.UserId==request.UserId);
            //开始事务
            using(var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (list != null) 
                    {
                        list.IsDelete = 1;
                        await baseRepository.Update(list);
                        NlogInfo nlog = new NlogInfo();
                        nlog.NlogId=YitIdHelper.NextId();
                        nlog.NlogName = "删除操作";
                        nlog.NlogTime= DateTime.Now;
                        nlog.Context = $"删除了一条编号为{request.UserId}的操作";
                        await baseRepository1.Add(nlog);
                        //提交事务
                        tran.Complete();
                    }

                    return await Task.FromResult(result);
                }
                catch (Exception)
                {

                    throw;
                }

            }
        }
    }
}
